/*****************************************************************************
 * Copyright (c) 2010 -, Anders All rights reserved
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *  Contact: Anders Uddenberg (anders.uddenberg@gmail.com)
 * 
 *
 ****************************************************************************/
package org.easypr.organizer.client.presenter;


import java.util.ArrayList;

import org.easypr.organizer.client.BackboneServiceAsync;
import org.easypr.organizer.client.event.DisplayInformationEvent;
import org.easypr.organizer.shared.MyContact;
import org.easypr.organizer.shared.MyUser;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

// TODO: Auto-generated Javadoc
/**
 * The Class MenuPresenter.
 */
public class ImportPresenter implements Presenter {

	/**
	 * Define the interface the view needs to implement.
	 * 
	 * @author Anders
	 */
	public interface Display {
		
		/**
		 * Sets the data.
		 *
		 * @param user the user
		 * @param contacts the contacts
		 */
		void setData(MyUser user, ArrayList<MyContact> contacts);

		/**
		 * As widget.
		 * 
		 * @return the widget
		 */
		Widget asWidget();
		
		/**
		 * Gets the import link.
		 *
		 * @return the import link
		 */
		Anchor getImportLink();
		
		/**
		 * Gets the next link.
		 *
		 * @return the next link
		 */
		Anchor getNextLink();
		
		/**
		 * Gets the boxes.
		 *
		 * @return the boxes
		 */
		ArrayList<CheckBox> getBoxes();
		
		/**
		 * Gets the contacts.
		 *
		 * @return the contacts
		 */
		ArrayList<MyContact> getContacts();
		
		/**
		 * Gets the save status label.
		 *
		 * @return the save status label
		 */
		Label getSaveStatusLabel();
		
	}

	/** The event bus. */
	private final HandlerManager eventBus;
	
	/** The display. */
	private final Display display;
	
	/** The backbone rpc. */
	private BackboneServiceAsync backboneRPC;
	
	
	
	/** The user. */
	private MyUser user;
	
	/** The parts. */
	@SuppressWarnings("unused")
	private String[] parts;
	
	/** The saved. */
	private int saved = 0;
	
	/**
	 * Instantiates a new import presenter.
	 *
	 * @param backboneRPC the backbone rpc
	 * @param eventBus the event bus
	 * @param view the view
	 * @param user the user
	 * @param parts the parts
	 */
	public ImportPresenter(BackboneServiceAsync backboneRPC, HandlerManager eventBus, Display view, MyUser user, String[] parts) {
		this.backboneRPC = backboneRPC;
		this.eventBus = eventBus;
		this.display = view;
		this.user = user;
		this.parts = parts;
	}

	/* (non-Javadoc)
	 * @see org.easypr.organizer.client.presenter.Presenter#go(com.google.gwt.user.client.ui.HasWidgets)
	 */
	@Override
	public void go(HasWidgets container) {
		container.clear();
		container.add(display.asWidget());
		bind();
		updateContent();
	}
	
	/**
	 * Bind.
	 */
	private void bind() {
		display.getImportLink().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				saved = 0;
				ArrayList<CheckBox> boxes = display.getBoxes();
				ArrayList<MyContact> contacts = display.getContacts();
				
				
				for(int i=0;i<boxes.size(); i++) {
					if(boxes.get(i).getValue()) {
						AsyncCallback<MyContact> callback = new AsyncCallback<MyContact>() {
							public void onFailure(Throwable caught) {
								eventBus.fireEvent(new DisplayInformationEvent("Unable to import the user!", DisplayInformationEvent.Severity.FAILURE));
							}

							public void onSuccess(MyContact result) {
								saved++;
								String saveMessage;
								if(saved == 1) {
									saveMessage = "1 contact saved";
								} else {
									saveMessage = saved + " contacts saved";
								}
								display.getSaveStatusLabel().setText(saveMessage);
								
							}
						};
						int contactid = Integer.parseInt(boxes.get(i).getElement().getId());
						backboneRPC.saveContact(contacts.get(contactid), callback);
					}
				}
				if(saved > 0) {
					eventBus.fireEvent(new DisplayInformationEvent("Contacts successfully imported!", DisplayInformationEvent.Severity.SUCCESS));
				}
			}
		});
		
		display.getNextLink().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				AsyncCallback<String> callback = new AsyncCallback<String>() {
					public void onFailure(Throwable caught) {
						eventBus.fireEvent(new DisplayInformationEvent("Unable to proceed with the request!", DisplayInformationEvent.Severity.FAILURE));
					}

					public void onSuccess(String url) {
						updateContactList(url);
					}
				};
				
				backboneRPC.getImportNextLink(callback);
			}
		});
	}
	
	
	/**
	 * Update contact list.
	 *
	 * @param nextFeedURL the next feed url
	 */
	private void updateContactList(String nextFeedURL) {
		if(user.getAccessToken() != null && user.getAccessToken().length() > 0) {
			
			AsyncCallback<ArrayList<MyContact>> data_callback = new AsyncCallback<ArrayList<MyContact>>() {
				public void onFailure(Throwable caught) {
					eventBus.fireEvent(new DisplayInformationEvent("Unable to proceed with the request!", DisplayInformationEvent.Severity.FAILURE));
				}

				public void onSuccess(ArrayList<MyContact> contacts) {
					display.setData(user, contacts);
				}
				
			};
			
			backboneRPC.fetchGoogleContacts(user, nextFeedURL, data_callback);
			
		} else {
			display.setData(user, null);
		}
	}
	
	
	
	/**
	 * Main function to update the content of the container.
	 */
	public void updateContent() {
		this.updateContactList(null);
	}
	
}

